<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use fast\Random;
use think\Validate;
use think\Db;
use fast\Http;
use addons\third\library\Service;
use app\common\library\Auth;
use addons\third\model\Third;

/**
 * 会员接口
 */
class User extends Api
{
    protected $noNeedLogin = ['login', 'miniGetuserinfo', 'changemobile', 'third','miniapplogin'];
    protected $noNeedRight = '*';

    protected $token = '';
    public function _initialize()
    {
        $this->token = $this->request->post('token');
        if ($this->request->action() == 'login' && $this->token) {
            $this->request->post(['token' => '']);
        }
        parent::_initialize();
    }
  
    /**
     * 小程序获取用户授权数据的接口
     * @ApiSummary  (小程序用户授权后把头像和昵称信息储存到数据库)
     * @ApiMethod   (POST)
     * @ApiParams   (name="openid", type="string", required=true, description="微信openid")
     * @ApiParams   (name="rawData", type="string", required=true, description="微信获取的rawData")
     */
    public function miniGetuserinfo()
    {
        $openid = $this->request->post("openid");
        $rawData = $this->request->post("rawData");
        if (!$rawData) {
            $this->error($rawData);
        }

        $rawData = htmlspecialchars_decode($rawData);
        $userInfo = (array)json_decode($rawData, true);

        $platform = 'wxapp';
        $result = [
            'openid'        => $openid,
            'userinfo'      => [
                'nickname' => $userInfo['nickName'],
            ],
        ];
        $extend = ['gender' => $userInfo['gender'], 'nickname' => $userInfo['nickName'], 'avatar' => $userInfo['avatarUrl']];
        
        // 第三方登录入库
        $ret = Service::connect($platform, $result, $extend);
        if ($ret) {
            //登录成功后的用户数据操作
            $auth = Auth::instance();

            $this->success("微信授权成功", ['userInfo' => $auth->getUserinfo()]);
        } else {
            $this->error("微信授权失败");
        }
    }

    /**
     * 小程序登录接口
     * @ApiSummary  (小程序登录接口)
     * @ApiMethod   (POST)
     * @ApiParams   (name="code", type="string", required=true, description="微信获取的code")
     * @ApiReturnParams   (name="openid", type="string", required=true, description="openid")
     * @ApiReturnParams   (name="http_result", type="string", required=true, description="wx登录返回的数据")
     */
    public function miniapplogin()
    {
        $config = get_addon_config('third');    
        $config = $config['wechat'];

        $code = $this->request->post("code");
        if (!$code) {
            $this->error("参数不正确");
        }
        
        $params = [
            'appid'      => $config['app_id'],
            'secret'     => $config['app_secret'],
            'js_code'    => $code,
            'grant_type' => 'authorization_code'
        ];

        $http_result = Http::sendRequest("https://api.weixin.qq.com/sns/jscode2session", $params, 'GET');
        if ($http_result['ret']) {
            $json = (array)json_decode($http_result['msg'], true);

            if (isset($json['openid'])) {
                
                $platform = 'wxapp';
                $result = [
                    'openid'        => $json['openid'],
                    'access_token'  => $json['session_key'],
                    'expires_in'    => isset($json['expires_in']) ? $json['expires_in'] : 0,
                ];
                // 第三方登录入库
                // 在user表创建一条新用户数据
                $ret = Service::connect($platform, $result);
                if ($ret) {
                    //登录成功后的用户数据操作
                    $auth = Auth::instance();

                    $Index = new \app\api\controller\Index;
                    $Index->up_action();

                    $this->success("登录成功", ['http_result' => $json,'openid'=>$json['openid'],'token' => $auth->getUserinfo()['token']]);
                } else {
                    $this->error("连接失败");
                }
            } else {
                $this->error("登录失败",$http_result['msg']);
            }
        }

        return;
    }

    /**
     * 会员信息
     * @ApiSummary  (discount折扣多少折,experience个人经验值，land_num土地数量，money余额)
     * @ApiMethod   (GET)
     * @ApiReturnParams   (name="level", type="int", required=true, description="等级")
     * @ApiReturnParams   (name="experience", type="decimal", required=true, description="经验值")
     * @ApiReturnParams   (name="land_num", type="int", required=true, description="土地数量")
     * @ApiReturnParams   (name="money", type="decimal", required=true, description="余额用于提现")
     * @ApiReturnParams   (name="discount", type="decimal", required=true, description="商城折扣值")
     */
    public function index()
    {
        $user = $this->auth->getUserinfo();
        $this->success('会员信息', $user);
    }

    /**
     * 修改用户信息(手机号码，支付宝信息)
     * @param string $username 真实姓名
     * @param string $mobile 手机号码用于话费充值
     * @param string $zhifubao 支付宝账号
     */
    public function edit(){
        $user = $this->auth->getUser();
        $username = input('username');
        $mobile = input('mobile');
        $zhifubao = input('zhifubao');
     
        if($username){
            $user->username = $username;
        }
        if ($mobile) {
            $user->mobile = $mobile;
        }
        if($zhifubao){
            $user->zhifubao = $zhifubao;
        }
        
        $user->save();
        $this->success('修改成功');
    }

    
}
